package com.example.monitor.service;

import com.example.monitor.config.JwtTokenUtil;
import com.example.monitor.model.DO.User;
import com.example.monitor.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    // 注册用户
    public User registerUser(User user) {
        user.setPasswordHash(passwordEncoder.encode(user.getPasswordHash()));
        return userRepository.save(user);
    }

    // 实现UserDetailsService接口方法，用于登录认证
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("DEBUG-查询用户: " + username); // 添加调试日志
        // 修改为更安全的写法
        try {
            return userRepository.findByUsername(username)
                    .map(user -> {
                        System.out.println("DEBUG-找到用户: " + user.getUsername()); // 调试输出
                        return (UserDetails) user;
                    })
                    .orElseThrow(() -> {
                        System.out.println("DEBUG-用户不存在: " + username); // 调试输出
                        return new UsernameNotFoundException("用户不存在");
                    });
        } catch (Exception e) {
            System.err.println("加载用户时发生错误: " + e.getClass().getName() + ": " + e.getMessage());
            throw new UsernameNotFoundException("用户加载失败", e);
        }
    }

    public Optional<String> loginUser(String username, String password) {
        try {
            UserDetails userDetails = this.loadUserByUsername(username);

            if (passwordEncoder.matches(password, userDetails.getPassword())) {
                // 添加日志输出便于调试
                System.out.println("为用户["+username+"]生成JWT令牌");
                String token = jwtTokenUtil.generateToken(userDetails);
                return Optional.of(token);
            }
            System.err.println("密码验证失败: " + username);
            return Optional.empty();
        } catch (UsernameNotFoundException e) {
            System.err.println("用户不存在: " + username);
            return Optional.empty();
        }
    }
}
